﻿/// <reference path="//Microsoft.WinJS.0.6/js/base.js" /> 
/// <reference path="//Microsoft.WinJS.0.6/js/ui.js" /> 
(function () {
    "use strict";

    //An object for saving the date of the last click (For the GetStickers AppBar button)
    var lastClick = [{ type: "getSticker", date: new Date('1991-05-09T05:51:50.417') },
                      { type: "gameSticker", date: new Date('1991-05-09T05:51:50.417') }
    ];

    function checkClick(type, interval) {
        var now = new Date();
        var i = 0;
        if (type == "gameSticker") i = 1;
        var nowH = now.getHours();
        var lcH = lastClick[i].date.getHours();

        if ((nowH - lcH) >= interval) {
            lastClick[i].date = now;
            return true;
        }
        else
            if (lastClick[i].date.getDate() != now.getDate() && lastClick[i].date.getHours() <= (24 - interval)) {
                lastClick[i].date = now;
                return true;
            };

        return false;
    };

    var duplikati = [
        //{ tim: , ime: '', pozicija: '', broj: '', slika: '', duplikati: 1 },
    ];

    var statistika = [];

    var albumArr;
    var teamsArr;
    var duplikatiArr = new WinJS.Binding.List(duplikati);
    var igraciArr = new WinJS.Binding.List();

    var groupedItems = igraciArr.createGrouped(
        function groupKeySelector(item) { return item.tim; },
        function groupDataSelector(item) { return item; }
    );

    function getGrouped() {
        return duplikatiArr.createGrouped(
                function groupKeySelector(item) { return item.tim; },
                function groupDataSelector(item) { return item; });
    }

    //FCreating a filtered list from Player stickers
    function getItemsFromTim(tim) {
        return igraciArr.createFiltered(function (item) { return item.tim === tim; });
    }

    //Creating a filtered list by teams (for Duplicates)
    function getDuplicatesFromTim(tim) {
        return duplikatiArr.createFiltered(function (item) { return item.tim === tim; });
    }

    //Creating a filtered list for Charm Search
    function getSearchedPlayer(player) {
        return igraciArr.createFiltered(function (item) {
            return item.ime.search(player) !== -1;
        });
    }

    //Creating a filtered list for Charm Search (for Duplicates)
    function getSearchedDuplicatePlayer(player) {
        return duplikatiArr.createFiltered(function (item) {
            return item.ime.search(player) !== -1;
        });
    }

    //=============== Functions for adding pictures =================
    //Function for checking if a sticker is already added to the album. Used in paketFlyout.js
    function checkDuplicate(item) {
        if (getSearchedPlayer(item.ime).length > 0)
            return false;
        else
            return true;
    }

    //Function for adding duplicate stickers. Used in paketFlyout.js
    function dodadiDuplikat(item) {
        var ima = false;
        duplikatiArr.forEach(function (elem) {
            if (elem.ime === item.ime) {
                elem.duplikati++;
                ima = true;
            };
        });
        if (!ima)
            duplikatiArr.push({ tim: item.tim, ime: item.ime, pozicija: item.pozicija, broj: item.broj, slika: item.slika, duplikati: 1 });
    };

    //===========================================

    //================ Deserialization/Serialization functions ===========================

    //Deserialization function
    function getFromLocal() {
        var applicationData = Windows.Storage.ApplicationData.current;
        var localFolder = applicationData.localFolder;

        //Setting last clicked data
        localFolder.getFileAsync("zemanje.txt").then(function (sampleFile) {
            return Windows.Storage.FileIO.readTextAsync(sampleFile);
        }).done(function (timestamp) {
            var item = JSON.parse(timestamp);
            
            lastClick[0] = { type: item[0].type, date: new Date(item[0].date) };
            lastClick[1] = { type: item[1].type, date: new Date(item[1].date) };
            
        }, function () {
            // Timestamp not found
        });

        //Setting data for added stickers
        localFolder.getFileAsync("myimages.txt").then(function (sampleFile) {
            return Windows.Storage.FileIO.readTextAsync(sampleFile);
        }).done(function (timestamp) {
            var item = JSON.parse(timestamp);
            for (var i in item) {
                igraciArr.push({ tim: item[i].tim, ime: item[i].ime, pozicija: item[i].pozicija, broj: item[i].broj, slika: item[i].slika });
            }
        }, function () {
            // Timestamp not found
        });

        //Setting data for duplicate stickers
        localFolder.getFileAsync("duplikati.txt").then(function (sampleFile) {
            return Windows.Storage.FileIO.readTextAsync(sampleFile);
        }).done(function (timestamp) {
            var item = JSON.parse(timestamp);
            for (var i in item) {
                duplikatiArr.push({ tim: item[i].tim, ime: item[i].ime, pozicija: item[i].pozicija, broj: item[i].broj, slika: item[i].slika, duplikati: item[i].duplikati });
            }

        }, function () {
            // Timestamp not found
        });
    }

    //A serialization function
    function saveToLocal() {
        var myImages = igraciArr.slice(0);
        var dupli = duplikatiArr.slice(0);
        var clickArr = new WinJS.Binding.List(lastClick);
        var clicks = clickArr.slice(0);

        var myImagesSerialized = JSON.stringify(myImages);
        var dupliSerialized = JSON.stringify(dupli);
        var zemanjeSerialized = JSON.stringify(clicks);

        // SAVE to local storage 
        var applicationData = Windows.Storage.ApplicationData.current;
        var localFolder = applicationData.localFolder;

        //Getting last clicked data
        localFolder.createFileAsync("zemanje.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
            .then(function (sampleFile) {
                return Windows.Storage.FileIO.writeTextAsync(sampleFile, zemanjeSerialized);
            });

        //Getting data for added stickers
        localFolder.createFileAsync("myimages.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
            .then(function (sampleFile) {
                return Windows.Storage.FileIO.writeTextAsync(sampleFile, myImagesSerialized);
            });

        //Getting data for duplicate stickers
        localFolder.createFileAsync("duplikati.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
            .then(function (sampleFile) {
                return Windows.Storage.FileIO.writeTextAsync(sampleFile, dupliSerialized);
            });
    }
    //===========================================

    function filter(arr, count) {
        var tmp = [];

        for (var i = 0; i < count; i++) {
            var flag = 1;
            arr.forEach(function (item) {
                if (item == i) flag = 0;
            });
            if (flag == 1) tmp.push(i);
        };

        return tmp;
    }

    //================== Web Service functions =========================

    //Function for getting data from a webService
    function zemiStats() {

        WinJS.xhr({ url: "http://erikberg.com/nba/standings.json" })
            .then(function complete(result) {
                var results = JSON.parse(result.response);
                for (var k = 1; k <= 15; k++) {
                    for (var i in results.standing) {
                        if (results.standing[i].conference === "WEST" && results.standing[i].rank === k)
                            statistika.push({
                                rank: results.standing[i].ordinal_rank,
                                ime: results.standing[i].first_name + " " + results.standing[i].last_name,
                                won: "Wins: " + results.standing[i].won,
                                lost: "Loses: " + results.standing[i].lost
                            });
                    }
                }
            }).done(function dodadiStatistika() {
                postaviStats();
            });
    };

    //Function for setting data from a webService
    function postaviStats() {
        var listView = document.getElementById("statsListView").winControl;
        listView.itemTemplate = document.getElementById("statsTemplate");
        listView.layout = new WinJS.UI.ListLayout();
        listView.itemDataSource = new WinJS.Binding.List(statistika).dataSource;
    };

    //===========================================

    var publicMembers = {
        albumArr: albumArr,
        teamsArr: teamsArr,
        igraciArr: igraciArr,
        filter: filter,
        playArr: groupedItems,
        duplikatiArr: duplikatiArr,
        checkClick: checkClick,
        getGrouped: getGrouped,
        getItemsFromTim: getItemsFromTim,
        getDuplicatesFromTim: getDuplicatesFromTim,
        checkDuplicate: checkDuplicate,
        saveToLocal: saveToLocal,
        getFromLocal: getFromLocal,
        zemiStats: zemiStats,
        stats: postaviStats,
        getSearchedPlayer: getSearchedPlayer,
        getSearchedDuplicatePlayer: getSearchedDuplicatePlayer,
        dodadiDuplikat: dodadiDuplikat
    };

    WinJS.Namespace.define("Data", publicMembers);
})();